<template>
    <view class="console">
        <!-- 顶部导航栏 -->
        <uni-nav-bar
            :title="'客服工作台'"
            :status-bar="true"
            fixed
            :border="false"
            background-color="#ffffff"
            @clickLeft="showUserMenu"
        >
            <template #left>
                <view class="user-info">
                    <image class="avatar" :src="serviceInfo?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
                </view>
            </template>
            <template #right>
                <view class="status-btns">
                    <!-- 连接状态指示器 -->
                    <view class="connection-status">
                        <view class="status-indicator" :class="{ 'connected': wsConnected, 'disconnected': !wsConnected }"></view>
                        <text class="status-text">{{ wsConnected ? '已连接' : '未连接' }}</text>
                    </view>
                    <!-- 声音控制 -->
                    <uni-icons 
                        type="sound" 
                        size="24" 
                        :color="soundEnabled ? '#1976d2' : '#999'" 
                        @click="toggleSound"
                    />
                    <!-- 状态控制按钮 -->
                    <uni-icons 
                        v-for="status in statusList" 
                        :key="status.value"
                        :type="getStatusIcon(status.value)"
                        size="24"
                        :color="serviceInfo?.status === status.value ? '#1976d2' : '#666'"
                        @click="updateServiceStatus(status.value)"
                    />
                </view>
            </template>
        </uni-nav-bar>

        <!-- 主要内容区 -->
        <view class="main">
            <!-- 左侧会话列表 -->
            <view class="session-list">
                <view class="list-header">
                    <text class="title">会话列表</text>
                    <view class="header-actions">
                        <uni-badge v-if="pendingSessions.length" :text="pendingSessions.length" type="error" />
                        <uni-icons type="refresh" size="20" @click="refreshSessionsWithSound" />
                    </view>
                </view>

                <!-- 待分配会话 -->
                <scroll-view class="pending-sessions" scroll-y v-if="pendingSessions.length">
                    <view class="section-title attention">
                        <uni-icons type="notification-filled" size="18" color="#ff5722" />
                        <text>待分配会话 ({{ pendingSessions.length }})</text>
                    </view>
                    <view 
                        v-for="session in pendingSessions" 
                        :key="session.sessionId"
                        class="session-item pending"
                        :class="{'new-session': session.isNew}"
                    >
                        <view class="session-info">
                            <image class="user-avatar" :src="session.user?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
                            <view class="info">
                                <text class="user-name">{{ session.user?.username || session.user?.nickname || '未知用户' }}</text>
                                <text class="time">{{ formatTime(session.startTime) }}</text>
                                <text class="pending-message" v-if="session.lastMessage">{{ session.lastMessage }}</text>
                            </view>
                        </view>
                        <view class="actions">
                            <uni-button type="primary" size="mini" @click="acceptSession(session.sessionId)">接受</uni-button>
                            <uni-button type="error" size="mini" @click="showRejectDialog(session)">拒绝</uni-button>
                        </view>
                    </view>
                </scroll-view>

                <!-- 活跃会话 -->
                <scroll-view class="active-sessions" scroll-y>
                    <view class="section-title">
                        <uni-icons type="chat" size="16" color="#4caf50" />
                        <text>活跃会话</text>
                    </view>
                    <view 
                        v-for="session in activeSessions" 
                        :key="session.sessionId"
                        class="session-item"
                        :class="{ 
                            active: currentSession?.sessionId === session.sessionId,
                            'has-unread': session.unreadCount > 0
                        }"
                        @click="selectSession(session)"
                    >
                        <view class="session-info">
                            <image class="user-avatar" :src="session.user?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
                            <view class="info">
                                <text class="user-name">{{ session.user?.username || session.user?.nickname || '未知用户' }}</text>
                                <text class="last-message">{{ session.lastMessage || '暂无消息' }}</text>
                            </view>
                        </view>
                        <view class="meta">
                            <text class="time">{{ formatTime(session.lastTime || session.lastActiveTime || session.startTime) }}</text>
                            <uni-badge v-if="session.unreadCount" :text="session.unreadCount" type="error" />
                        </view>
                    </view>
                </scroll-view>
            </view>

            <!-- 右侧聊天区域 -->
            <view class="chat-area" v-if="currentSession">
                <view class="chat-header">
                    <view class="user-info">
                        <image class="user-avatar" :src="currentSession.user?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
                        <view class="info">
                            <text class="user-name">{{ currentSession.user?.username || currentSession.user?.nickname || '未知用户' }}</text>
                            <view class="session-details">
                                <text class="session-id">会话ID: {{ currentSession.sessionId }}</text>
                                <text class="session-time">开始时间: {{ formatDateTime(currentSession.startTime) }}</text>
                            </view>
                        </view>
                    </view>
                    <view class="actions">
                        <uni-button type="default" size="mini" @click="showTransferDialog">转接</uni-button>
                        <uni-button type="error" size="mini" @click="showEndDialog">结束</uni-button>
                    </view>
                </view>

                <scroll-view 
                    class="message-list" 
                    scroll-y 
                    :scroll-top="scrollTop"
                    @scrolltoupper="loadMoreMessages"
                >
                    <uni-load-more v-if="loading" status="loading" />
                    <view class="no-messages" v-if="!loading && (!messages || messages.length === 0)">
                        <text>暂无消息记录</text>
                    </view>
                    <view 
                        v-for="message in messages" 
                        :key="message.messageId"
                        class="message-item"
                        :class="{ 
                            'message-self': message.senderId === serviceInfo?.id || message.senderType === 'SERVICE',
                            'sending': message.status === 'SENDING',
                            'failed': message.status === 'FAILED'
                        }"
                    >
                        <image 
                            class="avatar"
                            :src="(message.senderId === serviceInfo?.id || message.senderType === 'SERVICE') ? serviceInfo?.avatar : currentSession.user?.avatar"
                            mode="aspectFill"
                        />
                        <view class="message-content">
                            <view class="message-sender">
                                <text>{{ (message.senderId === serviceInfo?.id || message.senderType === 'SERVICE') ? serviceInfo?.name : (currentSession.user?.username || currentSession.user?.nickname) }}</text>
                            </view>
                            <text class="message-text">{{ message.content }}</text>
                            <text class="message-time">{{ formatTime(message.timestamp) }}</text>
                        </view>
                    </view>
                </scroll-view>

                <view class="input-area">
                    <view class="toolbar">
                        <uni-icons type="emotion" size="24" @click="showEmojiPicker" />
                        <uni-icons type="camera" size="24" @click="chooseImage" />
                    </view>
                    <uni-easyinput
                        v-model="inputMessage"
                        type="textarea"
                        placeholder="请输入消息..."
                        :maxlength="500"
                        @confirm="sendMessage"
                    />
                    <button class="send-btn" @click="sendMessage">发送</button>
                </view>
            </view>

            <!-- 无会话时的提示 -->
            <view class="no-session" v-else>
                <uni-icons type="chat" size="64" color="#999" />
                <text>选择一个会话开始聊天</text>
            </view>
        </view>

        <!-- 用户菜单弹窗 -->
        <uni-popup ref="userMenu" type="bottom" background-color="#fff">
            <view class="popup-content">
                <view class="user-profile">
                    <image class="avatar" :src="serviceInfo?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
                    <view class="info">
                        <text class="username">{{ serviceInfo?.name }}</text>
                        <text class="email">{{ serviceInfo?.email }}</text>
                    </view>
                </view>
                <view class="menu-list">
                    <view class="menu-item" @click="showSettings">
                        <uni-icons type="gear" size="20" />
                        <text>设置</text>
                    </view>
                    <view class="menu-item" @click="showStatistics">
                        <uni-icons type="chart" size="20" />
                        <text>工作统计</text>
                    </view>
                    <view class="menu-item" @click="handleLogout">
                        <uni-icons type="logout" size="20" />
                        <text>退出登录</text>
                    </view>
                </view>
            </view>
        </uni-popup>

        <!-- 转接会话弹窗 -->
        <uni-popup ref="transferPopup" type="center">
            <view class="transfer-popup">
                <view class="popup-header">
                    <text class="title">转接会话</text>
                    <uni-icons type="close" size="20" @click="closeTransferPopup" />
                </view>
                <view class="popup-content">
                    <text class="label">选择客服</text>
                    <view class="service-list">
                        <view 
                            v-for="service in availableServices" 
                            :key="service.id"
                            class="service-item"
                            :class="{ active: selectedService?.id === service.id }"
                            @click="selectService(service)"
                        >
                            <image class="avatar" :src="service.avatar" mode="aspectFill" />
                            <view class="info">
                                <text class="name">{{ service.name }}</text>
                                <text class="status" :class="service.status.toLowerCase()">
                                    {{ getStatusText(service.status) }}
                                </text>
                            </view>
                        </view>
                    </view>
                    <text class="label">转接原因</text>
                    <uni-easyinput
                        v-model="transferReason"
                        type="textarea"
                        placeholder="请输入转接原因..."
                        :maxlength="200"
                    />
                </view>
                <view class="popup-footer">
                    <uni-button type="default" @click="closeTransferPopup">取消</uni-button>
                    <uni-button type="primary" @click="confirmTransfer">确认转接</uni-button>
                </view>
            </view>
        </uni-popup>

        <!-- 结束会话弹窗 -->
        <uni-popup ref="endPopup" type="center">
            <view class="end-popup">
                <view class="popup-header">
                    <text class="title">结束会话</text>
                    <uni-icons type="close" size="20" @click="closeEndPopup" />
                </view>
                <view class="popup-content">
                    <text class="label">结束原因</text>
                    <uni-easyinput
                        v-model="endReason"
                        type="textarea"
                        placeholder="请输入结束原因..."
                        :maxlength="200"
                    />
                </view>
                <view class="popup-footer">
                    <uni-button type="default" @click="closeEndPopup">取消</uni-button>
                    <uni-button type="error" @click="confirmEnd">确认结束</uni-button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { formatTime, formatDateTime } from '@/utils/date';
import {
    getActiveSessions,
    getPendingSessions,
    acceptSessionAssignment,
    rejectSessionAssignment,
    transferSession,
    endSession,
    sendMessage,
    loadMessages,
    updateServiceStatus,
    connectWebSocket,
    sendSessionMessage,
    sendServiceMessage
} from '@/api/chat';
import { logout } from '@/api/auth';
import websocketClient from '@/utils/websocket';

export default {
    data() {
        return {
            serviceInfo: null,
            statusList: [
                { label: '在线', value: 'ONLINE' },
                { label: '忙碌', value: 'BUSY' },
                { label: '离线', value: 'OFFLINE' }
            ],
            pendingSessions: [],
            activeSessions: [],
            currentSession: null,
            messages: [],
            inputMessage: '',
            scrollTop: 0,
            loading: false,
            emojis: ['😊', '😂', '😍', '🤔', '👍', '❤️', '😭', '😡', '🎉', '🙏'],
            availableServices: [],
            selectedService: null,
            transferReason: '',
            endReason: '',
            rejectSessionId: '',
            
            // 添加声音控制变量
            soundEnabled: true,
            
            // 添加连接状态变量
            wsConnected: false,
            reconnecting: false,
            
            // 添加音频对象
            sounds: {
                messageReceived: null,
                messageSent: null,
                notification: null,
                click: null,
                alert: null
            },
            
            // 上次提示音播放时间
            lastAlertTime: null,
            
            // 添加用户交互变量
            userInteracted: false
        };
    },

    methods: {
        formatTime,
        formatDateTime,
        
        getStatusIcon(status) {
            const iconMap = {
                'ONLINE': 'checkbox-filled',
                'BUSY': 'minus-square-filled',
                'OFFLINE': 'close-circle-filled'
            };
            return iconMap[status] || 'checkbox-filled';
        },

        showUserMenu() {
            this.playSound('click');
            this.$refs.userMenu.open();
        },

        showSettings() {
            this.playSound('click');
            uni.navigateTo({
                url: '/pages/settings/index'
            });
        },

        showStatistics() {
            this.playSound('click');
            uni.navigateTo({
                url: '/pages/service/statistics'
            });
        },

        handleLogout() {
            uni.showModal({
                title: '退出登录',
                content: '确定要退出登录吗？',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            // 调用退出登录API
                            const success = await logout();
                            if (!success) {
                                throw new Error('退出登录失败');
                            }
                            
                            // 清除本地存储
                        uni.clearStorageSync();
                            
                            // 跳转到登录页
                        uni.reLaunch({
                            url: '/pages/login/login'
                        });
                        } catch (error) {
                            console.error('退出登录失败:', error);
                            uni.showToast({
                                title: '退出登录失败',
                                icon: 'none'
                            });
                        }
                    }
                }
            });
        },

        getStatusText(status) {
            const statusMap = {
                'ONLINE': '在线',
                'BUSY': '忙碌',
                'OFFLINE': '离线'
            };
            return statusMap[status] || status;
        },

        async updateServiceStatus(status) {
            try {
                await updateServiceStatus(status);
                if(this.serviceInfo) {
                    this.serviceInfo.status = status;
                }
                uni.showToast({
                    title: '状态更新成功',
                    icon: 'success'
                });
            } catch (error) {
                uni.showToast({
                    title: '状态更新失败',
                    icon: 'error'
                });
            }
        },

        async refreshSessions() {
            try {
                console.log('刷新会话列表...');
                uni.showLoading({ title: '加载中...' });
                
                // 检查客服信息
                if (!this.serviceInfo) {
                    // 尝试从用户信息中获取客服信息
                    const userInfo = uni.getStorageSync('userInfo');
                    if (userInfo && userInfo.serviceInfo) {
                        this.serviceInfo = userInfo.serviceInfo;
                        console.log('从用户信息中获取客服信息:', JSON.stringify(this.serviceInfo));
                    } else if (userInfo && userInfo.userType === 'SERVICE') {
                        // 如果用户类型是客服但没有serviceInfo，创建一个临时的serviceInfo
                        this.serviceInfo = {
                            id: userInfo.userId || userInfo.id,
                            serviceCode: userInfo.username,
                            serviceType: 'HUMAN',
                            serviceStatus: 'ONLINE'
                        };
                        console.log('创建临时客服信息:', JSON.stringify(this.serviceInfo));
                    } else {
                        throw new Error('客服信息不完整，请重新登录');
                    }
                }
                
                // 确保客服信息中有ID
                if (!this.serviceInfo.id) {
                    const userInfo = uni.getStorageSync('userInfo');
                    if (userInfo && userInfo.userId) {
                        this.serviceInfo.id = userInfo.userId;
                        console.log('使用用户ID作为客服ID:', this.serviceInfo.id);
                    } else {
                        throw new Error('客服ID不存在，请重新登录');
                    }
                }
                
                console.log('当前客服ID:', this.serviceInfo.id);
                
                // 保存当前待分配会话的ID列表，用于检测新会话
                const currentPendingIds = this.pendingSessions.map(s => s.sessionId);
                
                // 使用Promise.allSettled代替Promise.all，以便即使一个请求失败也能处理另一个请求的结果
                const results = await Promise.allSettled([
                    getActiveSessions(),
                    getPendingSessions()
                ]);
                
                // 处理活跃会话结果
                if (results[0].status === 'fulfilled') {
                    const activeRes = results[0].value;
                console.log('活跃会话响应:', JSON.stringify(activeRes));
                    this.activeSessions = activeRes.data || [];
                } else {
                    console.error('获取活跃会话失败:', results[0].reason);
                    uni.showToast({
                        title: '获取活跃会话失败',
                        icon: 'none'
                    });
                }
                
                // 处理待处理会话结果
                if (results[1].status === 'fulfilled') {
                    const pendingRes = results[1].value;
                console.log('待处理会话响应:', JSON.stringify(pendingRes));
                
                    const newPendingSessions = pendingRes.data || [];
                    
                    // 检查是否有新的待分配会话
                    let hasNewSessions = false;
                    
                    // 标记新会话并播放通知声音
                    newPendingSessions.forEach(session => {
                        if (!currentPendingIds.includes(session.sessionId)) {
                            session.isNew = true;
                            hasNewSessions = true;
                        }
                    });
                    
                    // 更新待分配会话列表
                    this.pendingSessions = newPendingSessions;
                    
                    // 如果有新会话，播放通知声音
                    if (hasNewSessions && this.soundEnabled) {
                        this.playSound('notification');
                        
                        // 显示通知
                        uni.showToast({
                            title: '收到新的待处理会话',
                            icon: 'none',
                            duration: 3000
                        });
                        
                        // 5秒后移除新会话标记
                        setTimeout(() => {
                            this.pendingSessions.forEach(session => {
                                session.isNew = false;
                            });
                        }, 5000);
                    }
                } else {
                    console.error('获取待处理会话失败:', results[1].reason);
                    uni.showToast({
                        title: '获取待处理会话失败',
                        icon: 'none'
                    });
                }
                
                uni.hideLoading();
            } catch (error) {
                console.error('刷新会话失败:', error);
                uni.hideLoading();
                uni.showToast({
                    title: error.message || '刷新会话失败',
                    icon: 'none'
                });
                
                // 如果是客服信息不完整的错误，提示用户重新登录
                if (error.message && error.message.includes('客服信息不完整')) {
                    setTimeout(() => {
                        uni.showModal({
                            title: '登录已失效',
                            content: '请重新登录',
                            showCancel: false,
                            success: () => {
                                uni.reLaunch({
                                    url: '/pages/login/login'
                                });
                            }
                        });
                    }, 1000);
                }
            }
        },

        async selectSession(session) {
            this.playSound('click');
            this.currentSession = session;
            this.messages = [];
            await this.loadMessages();
        },

        async loadMessages() {
            if (this.loading || !this.currentSession) return;
            this.loading = true;
            
            try {
                console.log('加载消息历史:', this.currentSession.sessionId);
                // 使用最早消息ID作为分页标记
                const earliestMessageId = this.messages.length > 0 ? this.messages[0].messageId : null;
                
                const response = await loadMessages(
                    this.currentSession.sessionId,
                    earliestMessageId,
                    20
                );
                
                console.log('消息历史响应:', response);
                
                if (response && response.data) {
                    // 处理数组格式的历史消息
                    const historyMessages = response.data.records || response.data || [];
                    
                    if (historyMessages.length > 0) {
                        // 避免重复添加消息
                        const existingIds = new Set(this.messages.map(m => m.messageId));
                        const newMessages = historyMessages.filter(m => !existingIds.has(m.messageId));
                        
                        // 将新消息添加到列表前面，保持时间顺序
                        this.messages = [...newMessages, ...this.messages];
                    }
                }
            } catch (error) {
                console.error('加载消息失败:', error);
                
                // 检查是否是AI服务连接错误
                if (error.message && (
                    error.message.includes('Failed to connect to localhost') ||
                    error.message.includes('Connection refused') ||
                    error.message.includes('系统繁忙') ||
                    error.message.includes('暂时无法连接到AI服务')
                )) {
                    uni.showToast({
                        title: '暂时无法连接到AI服务，但您仍可以与用户交流',
                        icon: 'none',
                        duration: 3000
                    });
                } else {
                uni.showToast({
                    title: '加载消息失败',
                    icon: 'error'
                });
                }
            } finally {
                this.loading = false;
            }
        },

        async sendMessage(content) {
            // If content is provided, use it, otherwise use the input field
            const messageContent = content || this.inputMessage.trim();
            
            if (!messageContent || !this.currentSession) return;
            
            // Clear input field if we're using it
            if (!content) {
                this.inputMessage = '';
            }
            
            try {
                // 创建临时消息对象
                const tempMessage = {
                    messageId: 'temp_' + Date.now(),
                    sessionId: this.currentSession.sessionId,
                    senderId: this.serviceInfo.id,
                    senderType: 'SERVICE',
                    receiverId: this.currentSession.userId,
                    content: messageContent,
                    messageType: 'TEXT',
                    timestamp: new Date().toISOString(),
                    status: 'SENDING'
                };
                
                // 保存最后一条消息到本地存储，用于错误时重发
                uni.setStorageSync('last_message_' + this.currentSession.sessionId, {
                    content: messageContent,
                    timestamp: new Date().toISOString()
                });
                
                // 添加到消息列表
                this.messages.push(tempMessage);
                
                // 滚动到底部
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
                
                // 检查WebSocket是否已连接
                if (!this.wsConnected) {
                    console.log('WebSocket未连接，尝试重新连接...');
                    
                    // 尝试通过WebSocket发送
                    try {
                        const userInfo = uni.getStorageSync('userInfo');
                        if (userInfo && userInfo.id) {
                            await websocketClient.connect(userInfo.id);
                            this.wsConnected = true;
                        }
                    } catch (error) {
                        console.error('WebSocket重连失败:', error);
                    }
                }
                
                // 优先尝试通过WebSocket发送
                if (this.wsConnected) {
                    try {
                        await websocketClient.sendMessage({
                            type: 'CHAT',
                            sessionId: this.currentSession.sessionId,
                            senderId: this.serviceInfo.id,
                            senderType: 'SERVICE',
                            receiverId: this.currentSession.userId,
                            content: messageContent,
                            messageType: 'TEXT',
                            timestamp: new Date().toISOString(),
                            status: 'SENT'
                        });
                        
                        // 更新临时消息状态
                        const sentMessage = this.messages.find(m => m.messageId === tempMessage.messageId);
                        if (sentMessage) {
                            sentMessage.status = 'SENT';
                        }
                        
                        // 播放发送成功音效
                        this.playSound('sent');
                        
                        // 更新会话的最后一条消息
                        this.updateActiveSession(this.currentSession.sessionId, messageContent);
                        
                        return;
                    } catch (wsError) {
                        console.error('WebSocket发送失败，尝试HTTP发送:', wsError);
                    }
                }
                
                // 如果WebSocket发送失败，使用HTTP API发送
                console.log('尝试通过HTTP API发送消息...');
                const response = await sendServiceMessage(this.currentSession.sessionId, messageContent);
                
                console.log('发送消息响应:', response);
                
                // 更新临时消息状态
                const sentMessage = this.messages.find(m => m.messageId === tempMessage.messageId);
                if (sentMessage) {
                    if (response && response.data) {
                        // 更新为后端返回的消息
                        Object.assign(sentMessage, response.data, { status: 'SENT' });
                    } else {
                        sentMessage.status = 'SENT';
                    }
                }
                
                // 播放发送成功音效
                this.playSound('sent');
                
                // 更新会话的最后一条消息
                this.updateActiveSession(this.currentSession.sessionId, messageContent);
                
            } catch (error) {
                console.error('发送消息失败:', error);
                
                // 检查是否是AI模型错误
                if (error.message && (error.message.includes('Failed to communicate with Ollama API') ||
                    error.message.includes('AI模型暂时不可用'))) {
                    
                    console.warn('AI模型服务暂时不可用，但消息已发送');
                    
                    // 更新临时消息状态为已发送（尽管AI没有处理成功）
                    const tempMsg = this.messages.find(m => m.messageId && m.messageId.startsWith('temp_'));
                    if (tempMsg) {
                        tempMsg.status = 'SENT';
                    }
                    
                    // 播放提示音
                    this.playSound('sent');
                    
                    // 显示友好的提示
                    uni.showToast({
                        title: '消息已发送，但AI模型暂时不可用',
                        icon: 'none',
                        duration: 2000
                    });
                    
                    // 更新会话的最后一条消息
                    this.updateActiveSession(this.currentSession.sessionId, messageContent);
                    
                    return;
                }
                
                // 更新临时消息状态为失败
                const failedMessage = this.messages.find(m => m.messageId && m.messageId.startsWith('temp_'));
                if (failedMessage) {
                    failedMessage.status = 'FAILED';
                }
                
                uni.showToast({
                    title: '发送失败',
                    icon: 'error'
                });
            }
        },

        async acceptSession(sessionId) {
            this.playSound('click');
            try {
                uni.showLoading({ title: '接受中...' });
                
                console.log(`开始接受会话，会话ID: ${sessionId}`);
                
                // 检查客服信息
                if (!this.serviceInfo || !this.serviceInfo.id) {
                    throw new Error('客服信息不完整，请重新登录');
                }
                
                // 使用更新后的API函数接受会话
                const response = await acceptSessionAssignment(sessionId);
                console.log('接受会话成功，响应:', response);
                
                // 播放接受成功音效
                this.playSound('sent');
                
                // 从待处理列表中移除会话
                this.pendingSessions = this.pendingSessions.filter(s => s.sessionId !== sessionId);
                
                // 刷新会话列表
                await this.refreshSessions();
                
                // 查找并选择新接受的会话
                const acceptedSession = this.activeSessions.find(s => s.sessionId === sessionId);
                if (acceptedSession) {
                    // 选择会话并加载消息
                    await this.selectSession(acceptedSession);
                    
                            // 向用户发送WebSocket通知
                            try {
                        await websocketClient.sendMessage({
                                    type: 'SESSION_ACCEPTED',
                                    sessionId: sessionId,
                                    serviceId: this.serviceInfo.id,
                            serviceName: this.serviceInfo.name || '客服',
                            content: `您的会话已被客服接受`,
                            timestamp: new Date().toISOString(),
                            status: 'SENT'
                                });
                        console.log('已发送会话接受通知');
                            } catch (wsError) {
                                console.error('发送接受通知失败:', wsError);
                            }
                            
                    // 发送欢迎消息
                    setTimeout(() => {
                        if (this.currentSession && this.currentSession.sessionId === sessionId) {
                            // 准备欢迎消息
                            const welcomeContent = `您好，我是${this.serviceInfo.name || '客服'}，很高兴为您服务，请问有什么可以帮助您的？`;
                            
                            // 添加临时消息到界面
                            const welcomeMsg = {
                                messageId: 'welcome_' + Date.now(),
                                sessionId: sessionId,
                                senderId: this.serviceInfo.id,
                                senderType: 'SERVICE',
                                content: welcomeContent,
                                messageType: 'TEXT',
                                timestamp: new Date().toISOString(),
                                status: 'SENDING'
                            };
                            
                            this.messages.push(welcomeMsg);
                            this.scrollToBottom();
                            
                            // 发送实际消息
                            this.sendMessage(welcomeContent);
                        }
                    }, 500);
                
                uni.hideLoading();
                uni.showToast({
                    title: '已接受会话',
                    icon: 'success'
                });
                } else {
                    console.warn('接受会话成功，但未在活跃会话列表中找到该会话');
                    uni.hideLoading();
                    
                    // 再次刷新会话列表
                    setTimeout(() => {
                        this.refreshSessions();
                    }, 1000);
                    
                    uni.showToast({
                        title: '已接受会话，正在加载...',
                        icon: 'success'
                    });
                }
            } catch (error) {
                console.error('接受会话失败:', error);
                uni.hideLoading();
                
                // 播放错误提示音
                this.playSound('notification');
                
                // 显示详细错误信息
                uni.showModal({
                    title: '接受会话失败',
                    content: error.message || '无法接受会话，请稍后再试',
                    showCancel: false
                });
            }
        },

        showRejectDialog(session) {
            this.playSound('click');
            this.rejectSessionId = session.sessionId;
            uni.showModal({
                title: '拒绝会话',
                content: '请输入拒绝原因',
                editable: true,
                placeholderText: '例如：当前忙碌，无法接待',
                success: async (res) => {
                    if (res.confirm) {
                        const reason = res.content || '客服当前无法接待';
                        try {
                            uni.showLoading({ title: '处理中...' });
                            
                            console.log(`开始拒绝会话，会话ID: ${this.rejectSessionId}, 原因: ${reason}`);
                            
                            // 检查客服信息
                            if (!this.serviceInfo || !this.serviceInfo.id) {
                                throw new Error('客服信息不完整，请重新登录');
                            }
                            
                            // 直接使用改进后的rejectSessionAssignment函数，它已经包含了重试逻辑
                            const response = await rejectSessionAssignment(this.rejectSessionId, reason);
                            console.log('拒绝会话成功，响应:', response);
                            
                            // 发送WebSocket通知给用户
                            try {
                                await websocketClient.sendMessage({
                                    type: 'SESSION_REJECTED',
                                    sessionId: this.rejectSessionId,
                                    serviceId: this.serviceInfo.id,
                                    serviceName: this.serviceInfo.name || '客服',
                                    content: reason,
                                    status: 'SENT',
                                    timestamp: new Date().toISOString()
                                });
                                console.log('已发送拒绝通知');
                            } catch (wsError) {
                                console.error('发送拒绝通知失败:', wsError);
                            }
                            
                            uni.hideLoading();
                            // 播放操作成功音效
                            this.playSound('sent');
                            uni.showToast({
                                title: '已拒绝会话',
                                icon: 'success'
                            });
                            
                            // 从待分配列表中移除
                            this.pendingSessions = this.pendingSessions.filter(s => s.sessionId !== this.rejectSessionId);
                            this.rejectSessionId = '';
                        } catch (error) {
                            console.error('拒绝会话失败:', error);
                            uni.hideLoading();
                            
                            // 播放错误提示音
                            this.playSound('notification');
                            
                            // 显示详细错误信息
                            uni.showModal({
                                title: '拒绝会话失败',
                                content: error.message || '无法拒绝会话，请稍后再试',
                                showCancel: false
                            });
                        }
                    }
                }
            });
        },

        async showTransferDialog() {
            // 删除 getAvailableServices 的导入
            // 删除 getAvailableServices, 的导入
            // 删除 const response = await getAvailableServices(); 及相关逻辑
            // 如果有转接客服相关UI，建议一并注释或隐藏
        },

        async openTransferPopup() {
            this.$refs.transferPopup.open();
        },

        async confirmTransfer() {
            if (!this.selectedService || !this.currentSession) {
                this.closeTransferPopup();
                return;
            }
            
            uni.showLoading({ title: '处理中...' });
            
            transferSession(this.currentSession.sessionId, this.selectedService.id, this.transferReason)
                .then(response => {
                    console.log('转接会话响应:', response);
                    uni.hideLoading();
                    uni.showToast({
                        title: '会话已转接',
                        icon: 'success'
                    });
                    
                    // 移除当前会话
                    const index = this.activeSessions.findIndex(s => s.sessionId === this.currentSession.sessionId);
                    if (index > -1) {
                        this.activeSessions.splice(index, 1);
                    }
                    
                    // 发送会话转接通知消息
                    const transferMessage = {
                        messageId: 'system_' + Date.now(),
                        sessionId: this.currentSession.sessionId,
                        senderId: 'system',
                        senderType: 'SYSTEM',
                        content: `会话已转接给 ${this.selectedService.name}`,
                        messageType: 'SYSTEM',
                        timestamp: new Date(),
                        status: 'SENT'
                    };
                    
                    this.messages.push(transferMessage);
                    this.$nextTick(() => {
                        this.scrollToBottom();
                    });
                    
                    setTimeout(() => {
                        // 清空当前会话
                        this.currentSession = null;
                        this.messages = [];
                        this.selectedService = null;
                        this.transferReason = '';
                        this.closeTransferPopup();
                        
                        // 刷新会话列表
                        this.refreshSessions();
                    }, 2000);
                })
                .catch(error => {
                    console.error('转接会话失败:', error);
                    uni.hideLoading();
                    uni.showToast({
                        title: '转接失败',
                        icon: 'error'
                    });
                    this.closeTransferPopup();
                });
        },

        closeTransferPopup() {
            this.$refs.transferPopup.close();
        },

        showEndDialog() {
            this.playSound('click');
            this.$refs.endPopup.open();
        },

        confirmEnd() {
            this.playSound('click');
            if (!this.currentSession) {
                this.closeEndPopup();
                return;
            }
            
            uni.showLoading({ title: '处理中...' });
            
            endSession(this.currentSession.sessionId, this.endReason)
                .then(response => {
                    console.log('结束会话响应:', response);
                    uni.hideLoading();
                    // 播放操作成功音效
                    this.playSound('sent');
                    uni.showToast({
                        title: '会话已结束',
                        icon: 'success'
                    });
                    
                    // 移除当前会话
                    const index = this.activeSessions.findIndex(s => s.sessionId === this.currentSession.sessionId);
                    if (index > -1) {
                        this.activeSessions.splice(index, 1);
                    }
                    
                    // 发送会话结束通知消息
                    const endMessage = {
                        messageId: 'system_' + Date.now(),
                        sessionId: this.currentSession.sessionId,
                        senderId: 'system',
                        senderType: 'SYSTEM',
                        content: '会话已结束',
                        messageType: 'SYSTEM',
                        timestamp: new Date(),
                        status: 'SENT'
                    };
                    
                    this.messages.push(endMessage);
                    this.$nextTick(() => {
                        this.scrollToBottom();
                    });
                    
                    setTimeout(() => {
                        // 清空当前会话
                        this.currentSession = null;
                        this.messages = [];
                        this.closeEndPopup();
                        
                        // 刷新会话列表
                        this.refreshSessions();
                    }, 2000);
                })
                .catch(error => {
                    console.error('结束会话失败:', error);
                    uni.hideLoading();
                    // 播放错误提示音
                    this.playSound('notification');
                    uni.showToast({
                        title: '操作失败',
                        icon: 'error'
                    });
                    this.closeEndPopup();
                });
        },

        closeEndPopup() {
            this.$refs.endPopup.close();
        },

        showEmojiPicker() {
            uni.showActionSheet({
                itemList: this.emojis,
                success: (res) => {
                    this.inputMessage += this.emojis[res.tapIndex];
                }
            });
        },

        async chooseImage() {
            try {
                const res = await uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera']
                });
                
                if (res.tempFilePaths && res.tempFilePaths.length > 0) {
                    await this.uploadImage(res.tempFilePaths[0]);
                }
            } catch (error) {
                uni.showToast({
                    title: '选择图片失败',
                    icon: 'none'
                });
            }
        },

        async uploadImage(filePath) {
            try {
                const uploadRes = await uni.uploadFile({
                    url: '/chat/upload',
                    filePath: filePath,
                    name: 'file',
                    formData: {
                        sessionId: this.currentSession.sessionId
                    }
                });

                const result = JSON.parse(uploadRes.data);
                if (result.code === 200) {
                    await this.sendMessage(result.data.url, 'IMAGE');
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                uni.showToast({
                    title: '上传图片失败',
                    icon: 'none'
                });
            }
        },

        async selectService(service) {
            this.selectedService = service;
            await this.openTransferPopup();
        },

        // 添加WebSocket消息监听
        mounted() {
            // 检测用户交互
            if (typeof document !== 'undefined') {
                document.addEventListener('click', this.handleUserInteraction);
                document.addEventListener('touchstart', this.handleUserInteraction);
                document.addEventListener('keydown', this.handleUserInteraction);
            }
            
            // 设置WebSocket事件监听
            this.setupWebSocketListeners();
        },

        beforeDestroy() {
            // 移除用户交互检测
            if (typeof document !== 'undefined') {
                document.removeEventListener('click', this.handleUserInteraction);
                document.removeEventListener('touchstart', this.handleUserInteraction);
                document.removeEventListener('keydown', this.handleUserInteraction);
            }
            
            // 移除事件监听
            uni.$off('newMessage');
            uni.$off('systemMessage');
            uni.$off('transferMessage');
            
            // 关闭WebSocket连接
            const ws = uni.getStorageSync('websocket');
            if (ws) {
                ws.close();
            }
        },

        // 滚动到底部
        scrollToBottom() {
            this.$nextTick(() => {
                const query = uni.createSelectorQuery().in(this);
                query.select('.message-list').boundingClientRect(data => {
                    if (data) {
                        this.scrollTop = data.height * 100; // 足够大的值确保滚动到底部
                    }
                }).exec();
            });
        },

        // 添加加载更多消息的方法
        async loadMoreMessages() {
            if (this.loading || !this.currentSession) return;
            
            try {
                this.loading = true;
                const response = await loadMessages(
                    this.currentSession.sessionId,
                    this.messages.length / 20 + 1
                );
                
                if (response.data && response.data.length > 0) {
                    this.messages = [...response.data, ...this.messages];
                }
            } catch (error) {
                uni.showToast({
                    title: error.message || '加载更多消息失败',
                    icon: 'error'
                });
            } finally {
                this.loading = false;
            }
        },

        // 检查权限
        checkPermission() {
            const userRoles = uni.getStorageSync('userRoles') || [];
            const serviceInfo = uni.getStorageSync('serviceInfo');

            if (!userRoles.includes('ROLE_CUSTOMER_SERVICE') || !serviceInfo) {
                uni.showToast({
                    title: '您没有客服权限',
                    icon: 'none'
                });
                
                // 延迟跳转到首页
                setTimeout(() => {
                    uni.reLaunch({
                        url: '/pages/index/index'
                    });
                }, 1500);
                return;
            }
            
            // 继续加载客服数据
            this.serviceInfo = serviceInfo;
            this.loadSessions();
        },

        onLoad() {
            const userInfo = uni.getStorageSync('userInfo');
            if (!userInfo) {
                uni.showToast({
                    title: '请先登录',
                    icon: 'none'
                });
                setTimeout(() => {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    });
                }, 1500);
                return;
            }
            
            console.log('客服控制台初始化，用户信息:', JSON.stringify(userInfo));
            
            // 设置客服信息
            if (userInfo.serviceInfo) {
                // 使用嵌套的serviceInfo对象
                this.serviceInfo = userInfo.serviceInfo;
                console.log('使用嵌套的客服信息:', JSON.stringify(this.serviceInfo));
            } else if (userInfo.userType === 'SERVICE') {
                // 如果用户类型是客服但没有serviceInfo，创建一个临时的serviceInfo
                this.serviceInfo = {
                    id: userInfo.userId || userInfo.id,
                    name: userInfo.username || userInfo.nickname || '客服',
                    serviceCode: userInfo.username,
                    serviceType: 'HUMAN',
                    status: 'ONLINE'
                };
                console.log('创建临时客服信息:', JSON.stringify(this.serviceInfo));
            } else {
                // 不是客服用户，提示错误
                uni.showToast({
                    title: '您不是客服用户',
                    icon: 'none'
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
                return;
            }
            
            // 标记用户已交互，允许音频播放
            this.userInteracted = true;
            
            // 初始化音频
            this.initSounds();
            
            // 设置WebSocket事件监听
            this.setupWebSocketListeners();
            
            // 连接WebSocket
            this.connectWebSocket().then(() => {
                console.log('WebSocket连接成功，开始获取会话列表');
                // 立即刷新会话列表
                this.refreshSessionsWithSound();
            }).catch(error => {
                console.error('WebSocket连接失败:', error);
                // 即使WebSocket连接失败，也尝试刷新会话列表
                this.refreshSessionsWithSound();
            });
            
            // 设置定时刷新会话列表的定时器（每30秒刷新一次）
            this.refreshTimer = setInterval(() => {
                console.log('定时刷新会话列表...');
                this.refreshSessions().catch(error => {
                    console.error('定时刷新会话列表失败:', error);
                });
            }, 30000);
            
            // 在H5环境中添加用户交互监听，以确保音频可以播放
            // #ifdef H5
            if (typeof document !== 'undefined') {
                document.addEventListener('click', this.handleUserInteraction);
                document.addEventListener('touchstart', this.handleUserInteraction);
                document.addEventListener('keydown', this.handleUserInteraction);
            }
            // #endif
        },
        
        // 处理用户交互事件
        handleUserInteraction() {
            if (!this.userInteracted) {
                console.log('检测到用户交互，启用音频播放');
                this.userInteracted = true;
                
                // 预加载所有音频
                for (const key in this.sounds) {
                    if (this.sounds[key]) {
                        try {
                            this.sounds[key].load();
                        } catch (e) {
                            // 忽略加载错误
                        }
                    }
                }
            }
        },
        
        // 刷新会话并播放提示音
        refreshSessionsWithSound() {
            return this.refreshSessions().then(() => {
                // 如果有活跃会话或待处理会话，播放提示音
                if ((this.activeSessions && this.activeSessions.length > 0) || 
                    (this.pendingSessions && this.pendingSessions.length > 0)) {
                    
                    // 播放提示音
                    this.playSound('alert');
                }
            }).catch(error => {
                console.error('刷新会话失败:', error);
            });
        },

        // 播放声音(修改版本)
        playSound(type) {
            if (!this.soundEnabled) return;
            
            // 在H5环境中检查用户是否已交互
            // #ifdef H5
            if (!this.userInteracted) {
                console.log('用户尚未与页面交互，跳过声音播放');
                return;
            }
            // #endif
            
            try {
                let sound;
                switch(type) {
                    case 'received':
                        sound = this.sounds.messageReceived;
                    break;
                    case 'sent':
                        sound = this.sounds.messageSent;
                    break;
                    case 'notification':
                        sound = this.sounds.notification;
                    break;
                    case 'click':
                        sound = this.sounds.click;
                    break;
                    case 'alert':
                        // 确保alert使用正确的音频源
                        if (!this.sounds.alert || !this.sounds.alert.src.includes('tishi.mp3')) {
                            console.log('重新初始化提示音...');
                            this.sounds.alert = uni.createInnerAudioContext();
                            this.sounds.alert.src = '/static/sounds/tishi.mp3';
                            this.sounds.alert.autoplay = false;
                        }
                        sound = this.sounds.alert;
                        break;
                    default:
                        sound = this.sounds.messageSent;
                }
                
                if (sound) {
                    console.log(`播放声音: ${type}, 音频源: ${sound.src}`);
                    
                    try {
                        sound.stop();
                    } catch (e) {
                        // 忽略停止错误
                        console.warn('停止声音失败:', e);
                    }
                    
                    try {
                        sound.seek(0);
                    } catch (e) {
                        // 忽略seek错误
                        console.warn('重置声音位置失败:', e);
                    }
                    
                    // 使用setTimeout延迟播放，避免连续多次播放导致的错误
                    setTimeout(() => {
                        try {
                            sound.play();
                        } catch (e) {
                            console.error('播放声音失败:', e);
                            
                            // 如果播放失败，尝试重新创建音频对象
                            try {
                                if (type === 'alert') {
                                    this.sounds.alert = uni.createInnerAudioContext();
                                    this.sounds.alert.src = '/static/sounds/tishi.mp3';
                                    setTimeout(() => this.sounds.alert.play(), 100);
                                }
                            } catch (retryError) {
                                console.error('重试播放声音失败:', retryError);
                            }
                        }
                    }, 100);
                } else {
                    console.warn(`找不到声音类型: ${type}`);
                }
            } catch (error) {
                console.error('播放声音失败:', error);
            }
        },

        handleNewChatMessage(message) {
            console.log('收到新聊天消息:', message);
            
            // 验证消息格式
            if (!message.sessionId) {
                console.error('无效的消息格式: 缺少sessionId', message);
                return;
            }
            
            // 如果是当前会话的消息，添加到消息列表
            if (this.currentSession && message.sessionId === this.currentSession.sessionId) {
                // 生成一个临时ID如果消息没有ID
                if (!message.messageId) {
                    message.messageId = 'recv_' + Date.now();
                }
                
                // 检查消息是否已存在
                const existingMessage = this.messages.find(m => 
                    m.messageId === message.messageId || 
                    (m.content === message.content && 
                     m.senderId === message.senderId && 
                     Math.abs(new Date(m.timestamp) - new Date(message.timestamp)) < 5000)
                );
                
                if (!existingMessage) {
                    // 确保消息有状态
                    if (!message.status) {
                        message.status = 'SENT';
                    }
                    
                    this.messages.push(message);
                    this.scrollToBottom();
                    
                    // 播放提示音
                    this.playSound('received');
                }
            } else {
                // 如果不是当前会话，更新未读消息计数
                const session = this.activeSessions.find(s => s.sessionId === message.sessionId);
                if (session) {
                    if (!session.unreadCount) session.unreadCount = 0;
                    session.unreadCount++;
                    session.lastMessage = message.content;
                    session.lastTime = message.timestamp;
                    
                    // 将该会话移到顶部
                    const index = this.activeSessions.findIndex(s => s.sessionId === message.sessionId);
                    if (index > 0) {
                        const topSession = this.activeSessions.splice(index, 1)[0];
                        this.activeSessions.unshift(topSession);
                    }
                    
                    // 播放提示音提醒有新消息
                    this.playSound('alert');
                } else {
                    // 如果是新会话，刷新会话列表
                    console.log('收到新会话消息，刷新会话列表');
                    this.refreshSessions();
                }
            }
        },

        // 初始化音频
        initSounds() {
            try {
                // 创建音频对象
                this.sounds.messageReceived = uni.createInnerAudioContext();
                this.sounds.messageReceived.src = '/static/sounds/alter.mp3';
                this.sounds.messageReceived.preload = true;
                
                this.sounds.messageSent = uni.createInnerAudioContext();
                this.sounds.messageSent.src = '/static/sounds/success.mp3';
                this.sounds.messageSent.preload = true;
                
                this.sounds.notification = uni.createInnerAudioContext();
                this.sounds.notification.src = '/static/sounds/notification.mp3';
                this.sounds.notification.preload = true;
                
                this.sounds.click = uni.createInnerAudioContext();
                this.sounds.click.src = '/static/sounds/click.mp3';
                this.sounds.click.preload = true;
                
                // 添加提示音
                this.sounds.alert = uni.createInnerAudioContext();
                this.sounds.alert.src = '/static/sounds/tishi.mp3';
                this.sounds.alert.preload = true;
                
                // 从本地存储加载声音设置
                const soundSetting = uni.getStorageSync('service_sound_enabled');
                if (soundSetting !== undefined && soundSetting !== null) {
                    this.soundEnabled = soundSetting === 'true';
                }
                
                // 设置WebSocket客户端的声音状态
                websocketClient.setSoundsEnabled(this.soundEnabled);
                
                console.log('音频初始化成功，声音状态:', this.soundEnabled);
            } catch (error) {
                console.error('音频初始化失败:', error);
                this.soundEnabled = false;
            }
        },
        
        // 切换声音开关
        toggleSound() {
            this.soundEnabled = !this.soundEnabled;
            
            // 保存设置到本地存储
            uni.setStorageSync('service_sound_enabled', this.soundEnabled.toString());
            
            // 更新WebSocket客户端的声音状态
            websocketClient.setSoundsEnabled(this.soundEnabled);
            
            // 播放提示音以确认
            if (this.soundEnabled) {
                this.playSound('sent');
            }
            
            uni.showToast({
                title: this.soundEnabled ? '已开启声音' : '已关闭声音',
                icon: 'none'
            });
        },
        
        // 设置WebSocket事件监听
        setupWebSocketListeners() {
            // 先清除旧的监听器，避免重复
            this.clearWebSocketListeners();
            
            // 监听连接状态
            uni.$on('websocket-connected', (event) => {
                console.log('WebSocket连接已建立 (Event):', event);
                this.wsConnected = true;
                
                // 播放连接成功音效
                this.playSound('sent');
            });
            
            uni.$on('websocket-disconnected', (event) => {
                console.log('WebSocket连接已断开 (Event):', event);
                this.wsConnected = false;
                
                // 显示断开连接提示
                uni.showToast({
                    title: '连接已断开，正在重连...',
                    icon: 'none',
                    duration: 2000
                });
            });
            
            uni.$on('websocket-error', (error) => {
                console.error('WebSocket错误 (Event):', error);
                this.wsConnected = false;
            });
            
            // 监听新消息
            uni.$on('new-chat-message', (message) => {
                this.handleNewChatMessage(message);
            });

            // 监听系统消息
            uni.$on('system-message', (message) => {
                this.handleSystemMessage(message);
            });

            // 监听转接消息
            uni.$on('transfer-message', (message) => {
                this.handleTransferMessage(message);
            });
            
            // 监听会话分配消息
            uni.$on('session-assigned', (message) => {
                this.handleSessionAssigned(message);
            });
            
            // 监听会话结束消息
            uni.$on('session-ended', (message) => {
                this.handleSessionEnded(message);
            });
            
            // 监听错误消息
            uni.$on('error-message', (message) => {
                console.error('收到错误消息:', message);
                
                // 如果是消息处理失败，尝试通过HTTP重发
                if (message.content && message.content.includes('消息处理失败') && message.sessionId) {
                    if (this.currentSession && this.currentSession.sessionId === message.sessionId) {
                        // 尝试一次HTTP重发
                        setTimeout(() => {
                            const lastMessage = uni.getStorageSync('last_message_' + message.sessionId);
                            if (lastMessage && lastMessage.content) {
                                console.log('尝试通过HTTP API自动重发消息...');
                                sendSessionMessage(message.sessionId, lastMessage.content)
                                    .then(res => {
                                        console.log('自动重发成功:', res);
                                        uni.showToast({
                                            title: '消息已重发',
                                            icon: 'success'
                                        });
                                    })
                                    .catch(err => {
                                        console.error('自动重发失败:', err);
                                    });
                            }
                        }, 1000);
                    }
                }
            });
        },
        
        // 清除WebSocket事件监听
        clearWebSocketListeners() {
            uni.$off('websocket-connected');
            uni.$off('websocket-disconnected');
            uni.$off('websocket-error');
            uni.$off('new-chat-message');
            uni.$off('system-message');
            uni.$off('transfer-message');
            uni.$off('session-assigned');
            uni.$off('session-ended');
            uni.$off('error-message');
        },
        
        // 更新活跃会话信息
        updateActiveSession(sessionId, lastMessage) {
            // 查找并更新活跃会话列表中的会话
            const activeSessionIndex = this.activeSessions.findIndex(s => s.sessionId === sessionId);
            if (activeSessionIndex !== -1) {
                this.activeSessions[activeSessionIndex].lastMessage = lastMessage;
                this.activeSessions[activeSessionIndex].lastTime = new Date();
                
                // 将当前会话移到顶部
                const currentSession = this.activeSessions.splice(activeSessionIndex, 1)[0];
                this.activeSessions.unshift(currentSession);
            }
        },
        
        // 连接WebSocket
        async connectWebSocket() {
            try {
                const userInfo = uni.getStorageSync('userInfo');
                if (!userInfo || (!userInfo.id && !userInfo.userId)) {
                    throw new Error('未找到用户信息');
                }
                
                const userId = userInfo.id || userInfo.userId;
                console.log('连接WebSocket，用户ID:', userId);
                
                // 避免重复连接
                if (websocketClient.isConnected) {
                    console.log('WebSocket已连接，无需重新连接');
                    this.wsConnected = true;
                    return;
                }
                
                // 如果正在连接中，等待连接完成
                if (websocketClient.connecting) {
                    console.log('WebSocket正在连接中，等待连接完成...');
                    
                    // 等待连接完成或超时
                    return new Promise((resolve) => {
                        const checkConnected = () => {
                            if (websocketClient.isConnected) {
                                this.wsConnected = true;
                                resolve(true);
                                return;
                            }
                            
                            // 如果不再处于连接中状态，说明连接失败
                            if (!websocketClient.connecting) {
                                this.wsConnected = false;
                                resolve(false);
                                return;
                            }
                            
                            // 继续等待
                            setTimeout(checkConnected, 500);
                        };
                        
                        // 开始检查
                        checkConnected();
                    });
                }
                
                await websocketClient.connect(userId);
                this.wsConnected = true;
                
                console.log('WebSocket连接成功');
            } catch (error) {
                console.error('WebSocket连接失败:', error);
                this.wsConnected = false;
                
                // 显示错误提示
                uni.showToast({
                    title: '连接服务器失败，将在后台重试',
                    icon: 'none',
                    duration: 2000
                });
            }
        },

        handleSystemMessage(message) {
            console.log('收到系统消息:', message);
            
            uni.showToast({
                title: message.content,
                icon: 'none',
                duration: 3000
            });
            
            // 刷新会话列表
            this.refreshSessions();
        },

        handleSessionAssigned(message) {
            console.log('会话已分配:', message);
            
            // 刷新会话列表
            this.refreshSessions();
            
            // 播放提示音
            this.playSound('alert');
            
            // 显示通知
            uni.showToast({
                title: '收到新会话分配',
                icon: 'success'
            });
        },

        handleSessionEnded(message) {
            console.log('会话已结束:', message);
            
            // 如果是当前会话，显示结束消息
            if (this.currentSession && message.sessionId === this.currentSession.sessionId) {
                const endMessage = {
                    messageId: 'system_' + Date.now(),
                    sessionId: this.currentSession.sessionId,
                    senderId: 'system',
                    senderType: 'SYSTEM',
                    content: message.content || '会话已结束',
                    messageType: 'SYSTEM',
                    timestamp: new Date(),
                    status: 'SENT'
                };
                
                this.messages.push(endMessage);
                this.scrollToBottom();
                
                // 延迟清空当前会话
                setTimeout(() => {
                    // 从活跃会话中移除
                    const index = this.activeSessions.findIndex(s => s.sessionId === message.sessionId);
                    if (index > -1) {
                        this.activeSessions.splice(index, 1);
                    }
                    
                    // 如果当前正在查看这个会话，清空它
                    if (this.currentSession && this.currentSession.sessionId === message.sessionId) {
                        this.currentSession = null;
                        this.messages = [];
                    }
                }, 2000);
            } else {
                // 从活跃会话中移除
                const index = this.activeSessions.findIndex(s => s.sessionId === message.sessionId);
                if (index > -1) {
                    this.activeSessions.splice(index, 1);
                }
            }
        }
    }
};
</script>

<style lang="scss">
.console {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f5f6fa;
    padding-top: 88rpx;

    .user-info {
        display: flex;
        align-items: center;
        padding: 0 20rpx;

        .avatar {
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
            border: 2rpx solid #fff;
            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        }
    }

    .status-btns {
        display: flex;
        gap: 20rpx;
        padding-right: 20rpx;
    }

    .main {
        flex: 1;
        display: flex;
        overflow: hidden;

        .session-list {
            width: 400rpx;
    background-color: #fff;
            border-right: 2rpx solid #eee;
            display: flex;
            flex-direction: column;
            box-shadow: 2rpx 0 8rpx rgba(0, 0, 0, 0.05);

            .list-header {
                padding: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
                border-bottom: 2rpx solid #eee;
                background-color: #fff;

                .title {
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333;
                }

                .header-actions {
    display: flex;
    align-items: center;
                    gap: 20rpx;
                }
            }

            .pending-sessions,
            .active-sessions {
                flex: 1;
                overflow-y: auto;

                .section-title {
                    padding: 20rpx;
    font-size: 28rpx;
    color: #666;
                    background-color: #f5f6fa;
                    display: flex;
                    align-items: center;
                    gap: 10rpx;
                }

                .session-item {
                    padding: 20rpx;
                    border-bottom: 2rpx solid #eee;
                    cursor: pointer;
                    transition: all 0.3s ease;

                    &:hover {
                        background-color: #f5f6fa;
                        transform: translateX(4rpx);
                    }

                    &.active {
                        background-color: #e3f2fd;
                        border-left: 4rpx solid #1976d2;
                    }

                    &.pending {
                        background-color: #fff3e0;
                        border-left: 4rpx solid #ff9800;
                    }

                    .session-info {
                        display: flex;
                        align-items: center;
                        gap: 20rpx;
                        margin-bottom: 10rpx;

                        .user-avatar {
                            width: 80rpx;
                            height: 80rpx;
                            border-radius: 50%;
                            border: 2rpx solid #fff;
                            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
                        }

                        .info {
                            flex: 1;

                            .user-name {
                                font-size: 28rpx;
    font-weight: bold;
                                color: #333;
                            }

                            .last-message {
                                font-size: 24rpx;
                                color: #666;
                                margin-top: 8rpx;
                                white-space: nowrap;
                                overflow: hidden;
                                text-overflow: ellipsis;
                            }

                            .time {
                                font-size: 24rpx;
                                color: #999;
                                margin-top: 8rpx;
                            }
                        }
                    }

                    .meta {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .time {
    font-size: 24rpx;
                            color: #999;
                        }
                    }

                    .actions {
                        display: flex;
                        gap: 20rpx;
                        margin-top: 10rpx;
                    }
                }
            }
        }

        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #fff;

            .chat-header {
                padding: 20rpx;
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 2rpx solid #eee;
                background-color: #fff;
                box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

                .user-info {
                    display: flex;
                    align-items: center;
                    gap: 20rpx;

                    .user-avatar {
                        width: 80rpx;
                        height: 80rpx;
                        border-radius: 50%;
                        border: 2rpx solid #fff;
                        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
                    }

                    .info {
                        .user-name {
                            font-size: 32rpx;
                            font-weight: bold;
                            color: #333;
                        }

                        .session-details {
                            .session-id {
                                font-size: 24rpx;
                                color: #999;
                                margin-top: 8rpx;
                            }
                            .session-time {
                                font-size: 24rpx;
                                color: #999;
                                margin-top: 8rpx;
                            }
                        }
                    }
                }

                .actions {
                    display: flex;
                    gap: 20rpx;
                }
            }

            .message-list {
                flex: 1;
                padding: 20rpx;
                overflow-y: auto;

                .no-messages {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 200rpx;
                    color: #999;
                    font-size: 28rpx;
                }

                .message-item {
                    margin-bottom: 30rpx;
                    display: flex;
                    align-items: flex-start;
                    gap: 20rpx;

                    &.message-self {
                        flex-direction: row-reverse;

                        .message-content {
                            background-color: #e3f2fd;
                            border-radius: 20rpx 4rpx 20rpx 20rpx;
                            
                            .message-sender {
                                color: #1976d2;
                            }
                        }
                    }
                    
                    // System message styles
                    &[data-type="SYSTEM"] {
                        justify-content: center;
                        
                        .message-content {
                            background-color: rgba(0, 0, 0, 0.05);
                            color: #666;
                            border-radius: 20rpx;
                            padding: 10rpx 20rpx;
                            max-width: 70%;
                            text-align: center;
                            
                            .message-text {
                                font-size: 24rpx;
                            }
                            
                            .message-time {
                                display: none;
                            }
                        }
                        
                        .avatar {
                            display: none;
                        }
                    }

                    .avatar {
                        width: 80rpx;
                        height: 80rpx;
                        border-radius: 50%;
                        border: 2rpx solid #fff;
                        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
                    }

                    .message-content {
                        max-width: 60%;
                        padding: 20rpx;
                        background-color: #f5f5f5;
                        border-radius: 4rpx 20rpx 20rpx 20rpx;
                        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

                        .message-sender {
                            font-size: 28rpx;
                            font-weight: bold;
                            color: #333;
                            margin-bottom: 6rpx;
                        }

                        .message-text {
                            font-size: 28rpx;
                            line-height: 1.5;
                            word-break: break-all;
                        }

                        .message-time {
                            font-size: 24rpx;
                            color: #999;
                            margin-top: 10rpx;
                            display: flex;
                            justify-content: flex-end;
                            align-items: center;
                            
                            &:after {
                                content: '';
                                margin-left: 6rpx;
                                width: 12rpx;
                                height: 12rpx;
                                border-radius: 50%;
                                display: inline-block;
                            }
                        }
                    }
                }
            }

            .input-area {
                padding: 20rpx;
                border-top: 2rpx solid #eee;
    background-color: #fff;
                box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);

                .toolbar {
    display: flex;
                    gap: 20rpx;
                    margin-bottom: 10rpx;
                    padding: 0 20rpx;
                }

                .send-btn {
                    width: 120rpx;
                    height: 80rpx;
                    background-color: #1976d2;
                    color: #fff;
                    border: none;
                    border-radius: 8rpx;
                    font-size: 28rpx;
                    float: right;
                    margin-top: 10rpx;
                    transition: all 0.3s ease;

                    &:hover {
                        background-color: #1565c0;
                        transform: translateY(-2rpx);
                    }
                }
            }
        }

        .no-session {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background-color: #f5f6fa;
            gap: 20rpx;

            text {
                font-size: 28rpx;
                color: #999;
            }
        }
    }

    .popup-content {
        background-color: #fff;
        border-radius: 20rpx 20rpx 0 0;
        padding: 30rpx;

        .user-profile {
            display: flex;
            align-items: center;
            gap: 20rpx;
            padding-bottom: 30rpx;
            border-bottom: 2rpx solid #eee;

            .avatar {
                width: 120rpx;
                height: 120rpx;
                border-radius: 50%;
                border: 2rpx solid #fff;
                box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
            }

            .info {
                .username {
                    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

                .email {
                    font-size: 24rpx;
                    color: #666;
                    margin-top: 8rpx;
                }
            }
        }

        .menu-list {
            padding-top: 20rpx;

            .menu-item {
                display: flex;
                align-items: center;
                gap: 20rpx;
                padding: 20rpx 0;
                border-bottom: 2rpx solid #eee;
                transition: all 0.3s ease;

                &:hover {
                    background-color: #f5f6fa;
                    padding-left: 20rpx;
                }

                &:last-child {
                    border-bottom: none;
                }

                text {
                    font-size: 28rpx;
                    color: #333;
                }
            }
        }
    }

    .transfer-popup,
    .end-popup {
        background-color: #fff;
        border-radius: 20rpx;
        width: 600rpx;
        overflow: hidden;

        .popup-header {
            padding: 20rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2rpx solid #eee;

            .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}
        }

        .popup-content {
            padding: 20rpx;

            .label {
                font-size: 28rpx;
                color: #666;
                margin-bottom: 10rpx;
                display: block;
            }

            .service-list {
                margin-bottom: 20rpx;

                .service-item {
    display: flex;
    align-items: center;
                    gap: 20rpx;
    padding: 20rpx;
    border-radius: 8rpx;
                    cursor: pointer;
                    transition: all 0.3s ease;

                    &:hover {
                        background-color: #f5f6fa;
                    }

                    &.active {
                        background-color: #e3f2fd;
                        border: 2rpx solid #1976d2;
                    }

                    .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
                        border: 2rpx solid #fff;
                        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

                    .info {
    flex: 1;

                        .name {
    font-size: 28rpx;
                            font-weight: bold;
    color: #333;
}

                        .status {
    font-size: 24rpx;
                            padding: 4rpx 12rpx;
                            border-radius: 20rpx;
                            margin-top: 8rpx;
                            display: inline-block;

                            &.online {
                                background-color: #e8f5e9;
                                color: #4caf50;
                            }

                            &.busy {
                                background-color: #fff3e0;
                                color: #ff9800;
                            }

                            &.offline {
                                background-color: #f5f5f5;
                                color: #9e9e9e;
                            }
                        }
                    }
                }
            }
        }

        .popup-footer {
            padding: 20rpx;
            display: flex;
            justify-content: flex-end;
            gap: 20rpx;
            border-top: 2rpx solid #eee;
        }
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10rpx);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

// 消息状态样式
.message-self .message-content .message-time:after {
    content: '';
    background-color: #4caf50;
}

.message-item.sending .message-content .message-time:after {
    content: '';
    background-color: #FFC107;
}

.message-item.failed .message-content .message-time:after {
    content: '';
    background-color: #F44336;
}

/* 连接状态指示器样式 */
.connection-status {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
}

.status-indicator {
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    margin-right: 10rpx;
    
    &.connected {
        background-color: #4caf50;
        box-shadow: 0 0 10rpx rgba(76, 175, 80, 0.5);
    }
    
    &.disconnected {
        background-color: #f44336;
        box-shadow: 0 0 10rpx rgba(244, 67, 54, 0.5);
    }
}

.status-text {
    font-size: 24rpx;
    color: #666;
}

/* 消息状态样式 */
.message-item {
    &.sending .message-text {
        opacity: 0.7;
    }
    
    &.failed .message-text {
        color: #f44336;
        border: 1px solid #f44336;
    }
    
    .message-status {
        font-size: 20rpx;
        color: #999;
        margin-top: 4rpx;
    }
}

@keyframes pulse {
    0% {
        background-color: #fff3e0;
    }
    50% {
        background-color: #ffecb3;
    }
    100% {
        background-color: #fff3e0;
    }
}

@keyframes highlight {
    0% {
        background-color: #ffcdd2;
    }
    100% {
        background-color: #fff3e0;
    }
}
</style> 